# workers/makeword_worker.py
from PySide6.QtCore import QThread, Signal
import os
import csv
from docx import Document
from utils.log_util import LogUtil
import re

class MakeWordWorker(QThread):
    log_signal = Signal(str)  # 定义日志信号
    placeholders_signal = Signal(str)  # 定义占位符信号

    def __init__(self, template_path, csv_file_path, output_dir):
        super().__init__()
        self.template_path = template_path
        self.csv_file_path = csv_file_path
        self.output_dir = output_dir
        self.log_util = LogUtil(level='INFO')
        self.logger = self.log_util.get_logger()

    def run(self):
        try:
            # 确保输出目录存在
            if not os.path.exists(self.output_dir):
                os.makedirs(self.output_dir)
                self.log_signal.emit(f"创建输出目录: {self.output_dir}")

            # 检查模版文件是否存在
            if not os.path.exists(self.template_path):
                self.logger.error(f"Word 模版文件 {self.template_path} 不存在，请确保文件路径正确。")
                self.log_signal.emit(f"错误：Word 模版文件 {self.template_path} 不存在。")
                return

            # 检查 Word 模板文件中的占位符
            self.check_placeholders()

            # 尝试读取 CSV 文件，支持多种编码格式
            encodings_to_try = ['utf-8-sig', 'gbk', 'iso-8859-1']
            csv_data = None
            for encoding in encodings_to_try:
                try:
                    with open(self.csv_file_path, 'r', encoding=encoding) as csvfile:
                        csvreader = csv.reader(csvfile)
                        csv_data = list(csvreader)
                    self.log_signal.emit(f"成功使用编码 {encoding} 读取 CSV 文件。")
                    break
                except UnicodeDecodeError:
                    self.log_signal.emit(f"尝试使用编码 {encoding} 读取 CSV 文件失败，尝试下一个编码。")
                    continue

            if csv_data is None:
                self.log_signal.emit("无法读取 CSV 文件，请检查文件编码格式。")
                return

            # 获取字段名（第一行），并去除可能的BOM
            field_names = [field.strip().lstrip('\ufeff') for field in csv_data[0]]
            self.log_signal.emit(f"读取到的字段名: {field_names}")

            # 遍历每一行（从第二行开始，每一行对应一个教案）
            for row_idx in range(1, len(csv_data)):
                # 创建占位符替换字典
                replacements = {}
                for col_idx, field_name in enumerate(field_names):
                    placeholder = f"{{{{{field_name}}}}}"
                    replacements[placeholder] = csv_data[row_idx][col_idx]

                # 创建一个新的 Word 文档（基于模版）
                doc = Document(self.template_path)

                # 遍历文档中的每个段落，替换占位符
                for para in doc.paragraphs:
                    for placeholder, value in replacements.items():
                        if placeholder in para.text:
                            para.text = para.text.replace(placeholder, value)

                # 遍历文档中的每个表格，替换占位符
                for table in doc.tables:
                    for row in table.rows:
                        for cell in row.cells:
                            for para in cell.paragraphs:
                                for placeholder, value in replacements.items():
                                    if placeholder in para.text:
                                        para.text = para.text.replace(placeholder, value)

                # 生成新的 Word 文件名
                class_name = replacements.get('{{班级}}', '未知班级').strip('{}')
                student_id = replacements.get('{{学号}}', '未知学号').strip('{}')
                student_name = replacements.get('{{学生姓名}}', '未知姓名').strip('{}')

                # 清理文件名中的非法字符
                class_name = re.sub(r'[<>:"/\\|?*]', '_', class_name)
                student_id = re.sub(r'[<>:"/\\|?*]', '_', student_id)
                student_name = re.sub(r'[<>:"/\\|?*]', '_', student_name)

                new_word_filename = f"{class_name}_{student_id}_{student_name}.docx"
                new_word_path = os.path.join(self.output_dir, new_word_filename)

                self.log_signal.emit(f"生成新的 Word 文档: {new_word_filename}")

                # 保存新的 Word 文档
                doc.save(new_word_path)

        except Exception as e:
            self.logger.error(f"Word 生成任务出错: {e}")
            self.log_signal.emit(f"错误：Word 生成任务出错 - {e}")
        finally:
            self.logger.info("Word 生成任务结束")
            self.log_signal.emit("Word 生成任务结束")

    def check_placeholders(self):
        try:
            doc = Document(self.template_path)
            placeholders = set()

            # 遍历文档中的每个段落，查找占位符
            for para in doc.paragraphs:
                start = para.text.find('{{')
                while start != -1:
                    end = para.text.find('}}', start)
                    if end != -1:
                        placeholder = para.text[start:end + 2]
                        placeholders.add(placeholder)
                    start = para.text.find('{{', end)

            # 遍历文档中的每个表格，查找占位符
            for table in doc.tables:
                for row in table.rows:
                    for cell in row.cells:
                        for para in cell.paragraphs:
                            start = para.text.find('{{')
                            while start != -1:
                                end = para.text.find('}}', start)
                                if end != -1:
                                    placeholder = para.text[start:end + 2]
                                    placeholders.add(placeholder)
                                start = para.text.find('{{', end)

            self.placeholders_signal.emit(", ".join(placeholders))

        except Exception as e:
            self.logger.error(f"检查占位符时出错: {e}")
            self.log_signal.emit(f"错误：检查占位符时出错 - {e}")